package com.qujia.customer.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.qujia.common.config.QuJiaConfig;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.core.redis.RedisCache;
import com.qujia.common.enums.WxConsumptionMessageEnum;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.MathUtil;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.poi.ExcelUtil;
import com.qujia.coupon.domain.CouponInfo;
import com.qujia.coupon.domain.CouponIssue;
import com.qujia.coupon.domain.CouponIssueRelation;
import com.qujia.coupon.domain.CouponUser;
import com.qujia.coupon.mapper.CouponInfoMapper;
import com.qujia.coupon.mapper.CouponIssueMapper;
import com.qujia.coupon.mapper.CouponIssueRelationMapper;
import com.qujia.coupon.mapper.CouponUserMapper;
import com.qujia.customer.domain.*;
import com.qujia.customer.domain.dto.CardExcelItem;
import com.qujia.customer.domain.dto.ElectronicCardSubRes;
import com.qujia.customer.domain.dto.LabelRuleUser;
import com.qujia.customer.enums.CardRecordType;
import com.qujia.customer.mapper.CardExcelImportMapper;
import com.qujia.customer.mapper.CustomerCardUseRecordMapper;
import com.qujia.customer.mapper.CustomerElectronicCardMapper;
import com.qujia.customer.service.*;
import com.qujia.customer.vo.CalPresentAmt;
import com.qujia.enums.integralTypeEnum;
import com.qujia.integral.domain.CustomerPointsRecord;
import com.qujia.integral.mapper.CustomerPointsRecordMapper;
import com.qujia.integral.service.ICustomerPointsRecordService;
import com.qujia.label.domain.CustomerLabel;
import com.qujia.label.mapper.CustomerLabelMapper;
import com.qujia.label.mapper.LabelRuleMapper;
import com.qujia.system.domain.*;
import com.qujia.system.mapper.AppUserInfoUserMapper;
import com.qujia.system.mapper.GzhNewsTemplateMapper;
import com.qujia.system.mapper.SysEnterpriseUserMapper;
import com.qujia.system.mapper.SysStationUserMapper;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 客户电子会员卡充值消费记录Service业务层处理
 *
 * @author qujia
 * @date 2021-05-18
 */
@Service
public class CardExcelImportServiceImpl implements ICardExcelImportService
{

    public static final int BATCH_SIZE = 500;

    @Autowired
    private CardExcelImportMapper  cardExcelImportMapper;

    @Autowired
    private LabelRuleMapper  labelRuleMapper;


    @Autowired
    private AppUserInfoUserMapper appUserInfoUserMapper;

    @Autowired
    private CustomerElectronicCardMapper customerElectronicCardMapper;
    @Autowired
    private CustomerCardUseRecordMapper customerCardUseRecordMapper;

    @Autowired
    private SysStationUserMapper sysStationUserMapper;

    @Autowired
    private CustomerPointsRecordMapper customerPointsRecordMapper;

    @Autowired
    private CustomerLabelMapper customerLabelMapper;

    @Autowired
    private CouponIssueMapper couponIssueMapper;

    @Autowired
    private CouponInfoMapper couponInfoMapper;

    @Autowired
    private CouponIssueRelationMapper couponIssueRelationMapper;

    @Autowired
    private CouponUserMapper couponUserMapper;

    @Autowired
    private SysEnterpriseUserMapper sysEnterpriseUserMapper;

    @Autowired
    private GzhNewsTemplateMapper gzhNewsTemplateMapper;

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ICustomerElectronicCardService customerElectronicCardService;
    @Autowired
    private ICustomerCardSettingService customerCardSettingService;
    @Autowired
    private IReductionActivityBalanceRecordService reductionActivityBalanceRecordService;

    @Autowired
    private ActivityMessagePushRecordService activityMessagePushRecordService;
    @Autowired
    private ICustomerCardSettingDetailService customerCardSettingDetailService;

    @Autowired
    private ICustomerPointsRecordService customerPointsRecordService;



//    @Autowired
//    private ActivityMessagePushRecordService activityMessagePushRecordService;



    /**
     *  导入excel的客户信息
     *
     * @param id 客户信息的
     * @return 客户电子会员卡充值消费记录
     */
    @Override
    public CardExcelImport selectCardExcelImportById(Long id)
    {
        return cardExcelImportMapper.selectCardExcelImportById(id);
    }

    /**
     * 查询导入excel信息
     *
     * @param cardExcelImport  条件
     * @return 客户电子会员卡充值消费记录
     */
    @Override
    public List<CardExcelImport> selectCardExcelImportList(CardExcelImport  cardExcelImport)
    {
        return cardExcelImportMapper.selectCardExcelImportList(cardExcelImport);
    }



    /**
     * 校验手机号和油站信息查重
     *
     * @param cardExcelImport 校验手机号参数
     * @return 手机号的参数
     */
    @Override
    public List<CardExcelImport> selectCardExcelImportByPhoneStation(CardExcelImport  cardExcelImport){
        return cardExcelImportMapper.selectCardExcelImportList(cardExcelImport);
    }
    /**
     * 新增导入的信息
     *
     * @param cardExcelImport 新增的excel信息
     * @return 结果
     */
    @Override
    public int insertCardExcelImport(CardExcelImport cardExcelImport)
    {
       return cardExcelImportMapper.insertCardExcelImport(cardExcelImport);
    }

    /**
     * 修改导入的excel信息
     *
     * @param cardExcelImport 修改的导入客户信息
     * @return 结果
     */
    @Override
    public int updateCardExcelImport(CardExcelImport cardExcelImport)
    {
        return cardExcelImportMapper.updateCardExcelImport(cardExcelImport);
    }

    /**
     * 批量删除客户电子会员卡充值消费记录
     *
     * @param ids 需要删除的客户电子会员卡充值消费记录ID
     * @return 结果
     */
    @Override
    public int deleteCardExcelImportByIds(Long[] ids)
    {
        return cardExcelImportMapper.deleteCardExcelImportByIds(ids);
    }

    /**
     * 删除导入的客户信息
     *
     * @param id 客户电子会员卡充值消费记录ID
     * @return 结果
     */
    @Override
    public int deleteCardExcelImportById(Long id)
    {
        return cardExcelImportMapper.deleteCardExcelImportById(id);
    }



    @Transactional(rollbackFor =Exception.class )
    @Override
    public String importOne(CardExcelImport importData,List<SysAppUserInfoUser> appUserInfoUsers,Integer sendFalge,SysEnterpriseUser enterpriseUser, SysStationUser stationUser, GzhNewsTemplate gzhNewsTemplate) throws  Exception
    {

        String ordNooo="";
        SysAppUserInfoUser oldAppUser = null;
        if (importData.getChangePhone()) {
            // 是否替换旧手机号，首先判断有没有旧手机号
            SysAppUserInfoUser form = new SysAppUserInfoUser();
            form.setStationId(enterpriseUser.getEnterpriseId());
            form.setMobilePhone(importData.getOldPhoneNumber());
            oldAppUser = appUserInfoUserMapper.getOne(form);
            if (oldAppUser == null) {
//            newUserInfo = new SysAppUserInfoUser();
//            newUserInfo.setMobilePhone(newMobilePhone);
//            newUserInfo.setStationId(oldAppUser.getStationId());
                throw new CustomException("找不到旧手机号关联的用户");
            }
        }
        int successNum = 0;
        Long enterpriseId = enterpriseUser.getEnterpriseId();
        boolean cardUseForAll = StringUtils.equals("1",enterpriseUser.getCardUseRangeFlag());

        LoginUser loginUser= SecurityUtils.getLoginUser();
        //StringBuilder successMsg = new StringBuilder();


            SysAppUserInfoUser sysAppUserInfoUser1=new SysAppUserInfoUser();

           if(importData.getPhoneNumber()==null||"".equals(importData.getPhoneNumber())){
               throw new SQLException(" 手机号不能为空");
           }
                boolean updateflag=false;

                String erroMessage="";
//                for (CardExcelImport entry : existList) {
//                    if (entry.getPhoneNumber().equals(importData.getPhoneNumber())) {
//                        userFlag = true;
//                        erroMessage="已导入  ";
//                        break;
//                    }
//                }
                String format =new SimpleDateFormat("yyMMdd").format(new Date())+ RandomStringUtils.randomNumeric(5);
                sysAppUserInfoUser1.setMemberCode(format);
                sysAppUserInfoUser1.setRegisteDate(new Date());
        sysAppUserInfoUser1.setMobilePhone(importData.getPhoneNumber());
        sysAppUserInfoUser1.setGrowUpValue(Long.parseLong( importData.getGrowValue()+""));
        sysAppUserInfoUser1.setIntegral(Long.parseLong( importData.getIntegral()+""));
        sysAppUserInfoUser1.setStationId(enterpriseId);
                for (SysAppUserInfoUser appUserInfoUser : appUserInfoUsers) {
                    if (appUserInfoUser.getMobilePhone()!=null&&appUserInfoUser.getMobilePhone().equals(importData.getPhoneNumber())) {
                        updateflag=true;
                        sysAppUserInfoUser1.setUserId(appUserInfoUser.getUserId());
                        sysAppUserInfoUser1.setIntegral(Math.max(appUserInfoUser.getIntegral()+importData.getIntegral(),0));
                        sysAppUserInfoUser1.setGrowUpValue(Math.max((appUserInfoUser.getGrowUpValue()+importData.getGrowValue()),0));
                        sysAppUserInfoUser1.setMemberCode(appUserInfoUser.getMemberCode());
                        sysAppUserInfoUser1.setRegisteDate(null);
                        sysAppUserInfoUser1.setBlogOpenid(appUserInfoUser.getBlogOpenid());

                        List<CustomerElectronicCard> customerElectronicCards;

                        if (cardUseForAll) {
                            customerElectronicCards = customerElectronicCardService.getCustomerElectronicCardListForEnterprise(appUserInfoUser.getMobilePhone(), new String[]{importData.getCardType()}, enterpriseId);
                        }else {
                            customerElectronicCards = customerElectronicCardService.getCustomerElectronicCardListForStation(appUserInfoUser.getMobilePhone(),new String[]{importData.getCardType()},stationUser.getStationId());
                        }

                            if (customerElectronicCards != null && customerElectronicCards.size() == 1) {
                                CustomerElectronicCard customerElectronicCard1 = new CustomerElectronicCard();
                                customerElectronicCard1.setAmt(customerElectronicCards.get(0).getAmt().add(importData.getBalance()));
                                customerElectronicCard1.setId(customerElectronicCards.get(0).getId());
                                BigDecimal presentAmt = customerElectronicCards.get(0).getPresentAmt();
                                if(presentAmt==null){
                                    presentAmt=BigDecimal.ZERO;
                                }
                                Random random = new Random();
                                String result1 = "";
                                for (int i = 0; i < 6; i++) {
                                    result1 += random.nextInt(10);
                                }
                                String ordNo = System.nanoTime() + result1;
                                CustomerCardUseRecord customerCardUseRecord = new CustomerCardUseRecord();
                                customerCardUseRecord.setOrderNo(ordNo);
                                customerCardUseRecord.setCustomerNo(appUserInfoUser.getMemberCode());
                                customerCardUseRecord.setUsageType("+");
                                customerCardUseRecord.setPayType("imp");
                                customerCardUseRecord.setCardOilsType(importData.getCardType());
                                customerCardUseRecord.setAmt(importData.getBalance());
                                customerCardUseRecord.setIntegral(importData.getIntegral());
                                //customerCardUseRecord.setBalance(customerElectronicCards.get(0).getAmt().add(importData.getBalance()));
                                customerCardUseRecord.setCreateTime(new Date());
                                customerCardUseRecord.setStationId(Integer.parseInt(stationUser.getStationId() + ""));
                                customerCardUseRecord.setStatus("1");
                                customerCardUseRecord.setMobilePhone(importData.getPhoneNumber());
                                customerCardUseRecord.setEnterpriseId(enterpriseId);

                                if (importData.getIntegral() != null && importData.getIntegral() != 0) {
                                	CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();
                                    customerPointsRecord.setRecordType(importData.getIntegral().compareTo(0) > 0 ? "+" : "-");
                                    customerPointsRecord.setIntegral(Long.parseLong(importData.getIntegral() + ""));
                                    customerPointsRecord.setCreateTime(new Date());
                                    customerPointsRecord.setStationId(stationUser.getStationId());
                                    customerPointsRecord.setMobilePhone(importData.getPhoneNumber());
                                    customerPointsRecord.setAction(importData.getIntegral().compareTo(0) > 0 ? integralTypeEnum.MANUAL_ADDITION: integralTypeEnum.MANUAL_REDUCTION);
                                    customerPointsRecord.setOrderNo(ordNo);
                                    customerPointsRecordMapper.insertCustomerPointsRecord(customerPointsRecord);
                                    customerPointsRecordService.wxgzhIntegralPush(customerPointsRecord);

                                }

                                
                                if(importData.getBalance()!=null&&importData.getCardType()!=null&&importData.getBalance()!=BigDecimal.ZERO) {
                                    CalPresentAmt calPresentAmt = customerCardSettingDetailService.calPresentAmt(importData.getCardType(), importData.getBalance(), stationUser.getStationId(), enterpriseId, "xj",false);
                                    customerElectronicCard1.setPresentAmt(presentAmt.add(calPresentAmt.getPresentAmt()).setScale(2, BigDecimal.ROUND_HALF_UP));
                                    customerCardUseRecord.setPresentAmt(calPresentAmt.getPresentAmt());
                                    customerCardUseRecord.setCcsdId(calPresentAmt.getCcsdId());
                                    customerCardUseRecord.setBalance(MathUtil.add(customerElectronicCard1.getAmt(),customerElectronicCard1.getPresentAmt()));
                                    customerElectronicCardMapper.updateCustomerElectronicCard(customerElectronicCard1);
                                    customerCardUseRecordMapper.insertCustomerCardUseRecord(customerCardUseRecord);
                                    ordNooo=ordNo;
                                }


                            }
                            else {
                                CustomerElectronicCard customerElectronicCard1 = new CustomerElectronicCard();
                                customerElectronicCard1.setAmt(importData.getBalance());
                                customerElectronicCard1.setCustomerNo(appUserInfoUser.getMemberCode());
                                customerElectronicCard1.setMobilePhone(appUserInfoUser.getMobilePhone());
                                customerElectronicCard1.setCardOilsType(importData.getCardType());

                                customerElectronicCard1.setCreateTime(new Date());
                                if (!cardUseForAll) {
                                    // 单站使用
                                    customerElectronicCard1.setStationId2(stationUser.getStationId());
                                }else{
                                    // 多站通用
                                    customerElectronicCard1.setStationId(enterpriseId);
                                }

                                Random random = new Random();
                                String result1 = "";
                                for (int i = 0; i < 6; i++) {
                                    result1 += random.nextInt(10);
                                }
                                String ordNo = System.nanoTime() + result1;
                                CustomerCardUseRecord customerCardUseRecord = new CustomerCardUseRecord();
                                customerCardUseRecord.setOrderNo(ordNo);
                                customerCardUseRecord.setCustomerNo(appUserInfoUser.getMemberCode());
                                customerCardUseRecord.setUsageType("+");
                                customerCardUseRecord.setPayType("imp");
                                customerCardUseRecord.setCardOilsType(importData.getCardType());
                                customerCardUseRecord.setIntegral(importData.getIntegral());
                                customerCardUseRecord.setAmt(importData.getBalance());
                                //customerCardUseRecord.setBalance(BigDecimal.valueOf(0).add(importData.getBalance()));
                                customerCardUseRecord.setCreateTime(new Date());
                                customerCardUseRecord.setStationId(Integer.parseInt(stationUser.getStationId() + ""));
                                customerCardUseRecord.setStatus("1");
                                customerCardUseRecord.setMobilePhone(importData.getPhoneNumber());
                                customerCardUseRecord.setEnterpriseId(enterpriseId);
                                
                                if (importData.getIntegral() != null && importData.getIntegral() != 0) {
                                	CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();
                                    customerPointsRecord.setRecordType(importData.getIntegral().compareTo(0) > 0 ? "+" : "-");
                                    customerPointsRecord.setIntegral(Long.parseLong(importData.getIntegral() + ""));
                                    customerPointsRecord.setCreateTime(new Date());
                                    customerPointsRecord.setStationId(stationUser.getStationId());
                                    customerPointsRecord.setMobilePhone(importData.getPhoneNumber());
                                    customerPointsRecord.setAction(importData.getIntegral().compareTo(0) > 0 ? integralTypeEnum.MANUAL_ADDITION: integralTypeEnum.MANUAL_REDUCTION);
                                    customerPointsRecordMapper.insertCustomerPointsRecord(customerPointsRecord);
                                    customerPointsRecordService.wxgzhIntegralPush(customerPointsRecord);
                                }
                                if(importData.getBalance()!=null&&importData.getCardType()!=null&&importData.getBalance()!=BigDecimal.ZERO) {
                                    CalPresentAmt calPresentAmt = customerCardSettingDetailService.calPresentAmt(importData.getCardType(), importData.getBalance(), stationUser.getStationId(), enterpriseId, "xj",false);
                                    customerElectronicCard1.setPresentAmt(calPresentAmt.getPresentAmt());
                                    customerCardUseRecord.setPresentAmt(calPresentAmt.getPresentAmt());
                                    customerCardUseRecord.setCcsdId(calPresentAmt.getCcsdId());
                                    customerCardUseRecord.setBalance(MathUtil.add(customerElectronicCard1.getAmt(),customerElectronicCard1.getPresentAmt()));
                                    customerElectronicCardMapper.insertCustomerElectronicCard(customerElectronicCard1);
                                    customerCardUseRecordMapper.insertCustomerCardUseRecord(customerCardUseRecord);

                                }

                            }
                        break;
                        }


                }
//                if(importData.getCouponIssueId()!=null&&importData.getCouponIssueId()!="") {
//                    if (couponIssueMapper.selectCouponIssueById(importData.getCouponIssueId()) ==null) {
//                        issue = true;
//                        erroMessage=erroMessage+"  发放方式不存在";
//                    }
//                }
        if(!updateflag){


                CustomerElectronicCard customerElectronicCard1=new CustomerElectronicCard();
                customerElectronicCard1.setAmt(importData.getBalance());
                customerElectronicCard1.setCardOilsType(importData.getCardType());
                customerElectronicCard1.setCustomerNo(format);
                customerElectronicCard1.setMobilePhone(importData.getPhoneNumber());
                customerElectronicCard1.setCreateTime(new Date());
                if (!cardUseForAll) {
                    // 单站使用
                    customerElectronicCard1.setStationId2(stationUser.getStationId());
                }else{
                    // 多站通用
                    customerElectronicCard1.setStationId(enterpriseId);
                }
                    Random random=new Random();
                    String result1 = "";
                    for (int i = 0; i < 6; i++) {
                        result1 += random.nextInt(10);
                    }
                    String ordNo = System.nanoTime() + result1;
                    CustomerCardUseRecord customerCardUseRecord=new CustomerCardUseRecord();
                    customerCardUseRecord.setOrderNo(ordNo);
                    customerCardUseRecord.setCustomerNo(format);
                    customerCardUseRecord.setUsageType("+");
                    customerCardUseRecord.setPayType("imp");
                    customerCardUseRecord.setCardOilsType(importData.getCardType());
                    customerCardUseRecord.setAmt(importData.getBalance());
                    //customerCardUseRecord.setBalance(importData.getBalance());
                    customerCardUseRecord.setCreateTime(new Date());
                    customerCardUseRecord.setStationId(Integer.parseInt( stationUser.getStationId()+""));
                    customerCardUseRecord.setStatus("1");
                    customerCardUseRecord.setMobilePhone(importData.getPhoneNumber());
                    customerCardUseRecord.setIntegral(importData.getIntegral());
                    customerCardUseRecord.setEnterpriseId(enterpriseId);
                    
                    if (importData.getIntegral() != null && importData.getIntegral() != 0) {
                    	CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();
                        customerPointsRecord.setRecordType(importData.getIntegral().compareTo(0) > 0 ? "+" : "-");
                        customerPointsRecord.setIntegral(Long.parseLong(importData.getIntegral() + ""));
                        customerPointsRecord.setCreateTime(new Date());
                        customerPointsRecord.setStationId(stationUser.getStationId());
                        customerPointsRecord.setMobilePhone(importData.getPhoneNumber());
                        customerPointsRecord.setAction(importData.getIntegral().compareTo(0) > 0 ? integralTypeEnum.MANUAL_ADDITION: integralTypeEnum.MANUAL_REDUCTION);
                        customerPointsRecordMapper.insertCustomerPointsRecord(customerPointsRecord);
                        customerPointsRecordService.wxgzhIntegralPush(customerPointsRecord);
                    }
                    if(importData.getBalance()!=null&&importData.getCardType()!=null&&importData.getBalance()!=BigDecimal.ZERO) {
                        CalPresentAmt calPresentAmt = customerCardSettingDetailService.calPresentAmt(importData.getCardType(), importData.getBalance(), stationUser.getStationId(), enterpriseId, "xj",false);
                        customerElectronicCard1.setPresentAmt(calPresentAmt.getPresentAmt());
                        customerCardUseRecord.setPresentAmt(calPresentAmt.getPresentAmt());
                        customerCardUseRecord.setCcsdId(calPresentAmt.getCcsdId());
                        customerCardUseRecord.setBalance(MathUtil.add(customerElectronicCard1.getAmt(),customerElectronicCard1.getPresentAmt()));
                        customerCardUseRecordMapper.insertCustomerCardUseRecord(customerCardUseRecord);
                        customerElectronicCardMapper.insertCustomerElectronicCard(customerElectronicCard1);
                    }

        }
                //判断标签是否存在当前用户，不存在就进行添加
                if(importData.getLabelId()!=null&&importData.getLabelId()!=0) {
                    if (labelRuleMapper.selectLabelRuleById(importData.getLabelId())==null) {

                        throw new SQLException(erroMessage+"  标签不存在");

                    }else{
                        CustomerLabel customerLabel=new CustomerLabel();
                        customerLabel.setPhone(importData.getPhoneNumber());
                        customerLabel.setEnterpriseId(enterpriseId);
                        customerLabel.setDelFlag("0");
                        List<CustomerLabel> customerLabels=customerLabelMapper.selectCustomerLabelList(customerLabel);
                        if(customerLabels==null||customerLabels.size()==0){
                            customerLabel.setCreateTime(new Date());
                            customerLabel.setLabelId(importData.getLabelId());
                            customerLabelMapper.insertCustomerLabel(customerLabel);
                        }else {
                            CustomerLabel customerLabel1=new CustomerLabel();
                            customerLabel1.setDelFlag("1");
                            customerLabel1.setId(customerLabels.get(0).getId());
                            customerLabelMapper.updateCustomerLabel(customerLabel1);
                            customerLabel.setLabelId(importData.getLabelId());
                            customerLabel.setCreateTime(new Date());
                            customerLabelMapper.insertCustomerLabel(customerLabel);
                        }
                    }
                }

                if(importData.getCouponIssueId()!=null&&!importData.getCouponIssueId().equals("")){
                    CouponIssue couponIssue=couponIssueMapper.selectCouponIssueById(importData.getCouponIssueId());
                    if(couponIssue==null) {
                        throw  new  SQLException("当前发放方式不存在");
                    }else if(!couponIssue.getIssueType().equals("5")){
                        throw  new  SQLException("当前发放方式不支持批量发放");
                    }
                    else {
                        CouponIssueRelation couponIssueRelation=new CouponIssueRelation();
                        couponIssueRelation.setIssueId(importData.getCouponIssueId());
                        List<CouponIssueRelation> couponIssueRelations=couponIssueRelationMapper.selectCouponIssueRelationList(couponIssueRelation);
                        if(couponIssueRelations!=null&&couponIssueRelations.size()>0){
                            for(CouponIssueRelation couponIssueRelation1:couponIssueRelations){
                                CouponInfo couponInfo=couponInfoMapper.selectCouponInfoById(Integer.parseInt(couponIssueRelation1.getCouponId()+""));

                                 if(couponInfo ==null){
                                     throw new SQLException("查询不到当前的优惠券信息");
                                 }else if(couponInfo.getStatus().equals("0")) {
                                     throw new SQLException("优惠券已被停用");
                                 }else {

                                     if(couponInfo.getEffectiveTimeType().equals("1")){
                                        if(couponInfo.getEffectiveTimeEnd().before(new Date())){
                                            throw new SQLException("当前优惠券已经超过有效期");
                                        }
                                     }
                                     CouponUser couponUser1=new CouponUser();
                                     couponUser1.setCouponId(Long.parseLong(couponInfo.getId()+""));
                                     List<CouponUser> couponUsers=couponUserMapper.selectCouponUserList(couponUser1);
                                     if(couponUsers==null||couponUsers.size()==0){

                                     }else {
                                         if (couponInfo.getCouponNum() == couponUsers.size()) {
                                             throw new SQLException("当前优惠券数量不足");
                                         }
                                     }
                                     Date date=new Date();
                                     Calendar c = Calendar.getInstance();
                                     c.setTime(date);

                                     Date newDate = c.getTime();
                                     CouponInfo couponInfo1=new CouponInfo();
                                     couponInfo1.setId(couponInfo.getId());
                                     couponInfo1.setCouponNum(couponInfo.getCouponNum());
                                     couponInfo1.setGetCouponNum(couponInfo.getGetCouponNum()+1);
                                     couponInfoMapper.updateCouponInfo(couponInfo1);
                                     CouponUser couponUser=new CouponUser();
                                     couponUser.setEnterpriseId(enterpriseId);
                                     couponUser.setIssueId(couponIssue.getId());
                                     couponUser.setCouponId(Long.parseLong(couponInfo.getId()+""));
                                     couponUser.setCouponIsEffective("1");
                                     couponUser.setCouponIsUsed("0");
                                     couponUser.setCouponGetTime(new Date());
                                     couponUser.setMobilePhone(importData.getPhoneNumber());
                                     if(couponInfo.getEffectiveTimeType().equals("1")) {
                                         couponUser.setCouponEffectiveTime(couponInfo.getEffectiveTimeEnd());
                                     }else{
                                         c.add(Calendar.DATE,couponInfo.getEffectiveDayNum());
                                         couponUser.setCouponEffectiveTime(c.getTime());
                                     }
                                     couponUser.setCouponNo( useMD5(couponIssue.getEnterpriseId() + Long.toString(System.currentTimeMillis()) + Math.round((Math.random() + 1) * 1000)));
                                     couponUserMapper.insertCouponUser(couponUser);
                                 }
                            }
                        }else {
                            throw new SQLException("当前发放方式不存再优惠卷信息");
                        }
                    }

                }

//                if(importData.getMemberGrade()!=null&&!"".equals(importData.getMemberGrade())){
//                    if (customerGradeSettingMapper.selectCustomerGradeSettingById(Long.parseLong(importData.getMemberGrade()))==null) {
//                        grade = true;
//                        erroMessage=erroMessage+"   客户等级不存在";
//                    }
//                }
        Integer stationId = importData.getStationId();
        importData.setStationId(Integer.parseInt( enterpriseId+""));
        importData.setEnterpriseId(enterpriseId);
        importData.setCreateTime(new Date());
        importData.setCreateBy(loginUser.getUser().getUserId()+"");
        if(!updateflag) {
            appUserInfoUserMapper.insertAppUserInfo(sysAppUserInfoUser1);
        }else {
            appUserInfoUserMapper.updateAppUserInfo(sysAppUserInfoUser1);
            if(sendFalge==1&&!"".equals(sysAppUserInfoUser1.getBlogOpenid())&&sysAppUserInfoUser1.getBlogOpenid()!=null){
             push(sysAppUserInfoUser1.getBlogOpenid(),enterpriseUser,gzhNewsTemplate.getTemlateId(),sysAppUserInfoUser1.getIntegral()+"",importData.getIntegral()+"");
            }
        }
        //导入充值立减活动
        CustomerCardUseRecord customerCardUseRecord = new CustomerCardUseRecord();
        customerCardUseRecord.setPayType(CardRecordType.MANUAL_ADD.getKey());
        customerCardUseRecord.setCardOilsType(importData.getCardType());
        customerCardUseRecord.setAmt(importData.getBalance());
        customerCardUseRecord.setMobilePhone(importData.getPhoneNumber());
        customerCardUseRecord.setStationId(stationId);
        customerCardUseRecord.setEnterpriseId(enterpriseId);
        customerCardUseRecord.setSource("dtlr");//标识单条录入，进行消息推送
        customerCardUseRecord.setOrderNo(ordNooo);
        activityMessagePushRecordService.sendWxMessage(ActivityMessagePushRecord.TOPIC_REDUCTION_ACTIVITY, JSON.toJSONString(customerCardUseRecord), WxConsumptionMessageEnum.RECHARGE_REDUCTION_ACTIVITY);

        //充值送积分
//        customerCardUseRecord.setPayType("xj");
//        customerCardUseRecord.setMobilePhone(importData.getPhoneNumber());
//        customerElectronicCardService.rechargeActivityGiveIntegral(customerCardUseRecord);

       cardExcelImportMapper.insertCardExcelImport(importData);
        if (importData.getChangePhone()) {
            changeMobilePhone(oldAppUser,sysAppUserInfoUser1,enterpriseUser,stationUser,importData.getCardType());
        }
        return importData.getPhoneNumber();
    }

    private void changeMobilePhone(SysAppUserInfoUser oldAppUser,SysAppUserInfoUser newUserInfo,SysEnterpriseUser enterpriseUser,SysStationUser stationUser,String cardType) {
        //mergerUserInfo(newUserInfo, oldAppUser);
        Long integral = MathUtil.add(null, oldAppUser.getIntegral());
        Long growUpValue = MathUtil.add(null, oldAppUser.getGrowUpValue());
        Date now = new Date();
        if (integral>0 || growUpValue > 0) {
            SysAppUserInfoUser updateNewUser = new SysAppUserInfoUser();
            updateNewUser.setUserId(newUserInfo.getUserId());
            updateNewUser.setIntegral(MathUtil.add(newUserInfo.getIntegral(),oldAppUser.getIntegral()));
            updateNewUser.setGrowUpValue(MathUtil.add(newUserInfo.getGrowUpValue(),oldAppUser.getGrowUpValue()));
            appUserInfoUserMapper.updateAppUserInfo(updateNewUser);
            // 老的用户信息积分成长值清零
            SysAppUserInfoUser updateUser = new SysAppUserInfoUser();
            updateUser.setUserId(oldAppUser.getUserId());
            updateUser.setIntegral(0L);
            updateUser.setGrowUpValue(0L);
            appUserInfoUserMapper.updateAppUserInfo(updateUser);
            if (integral>0) {
                // 添加记录
                CustomerPointsRecord oldUserRecord = new CustomerPointsRecord();
                oldUserRecord.setRecordType("-");
                oldUserRecord.setIntegral(integral);
                oldUserRecord.setCreateTime(now);
                oldUserRecord.setStationId(stationUser.getStationId());
                oldUserRecord.setMobilePhone(oldAppUser.getMobilePhone());
                oldUserRecord.setAction(integralTypeEnum.MANUAL_REDUCTION);
                customerPointsRecordMapper.insertCustomerPointsRecord(oldUserRecord);
                CustomerPointsRecord newUserRecord = new CustomerPointsRecord();
                newUserRecord.setRecordType("+");
                newUserRecord.setIntegral(integral);
                newUserRecord.setCreateTime(now);
                newUserRecord.setStationId(stationUser.getStationId());
                newUserRecord.setMobilePhone(newUserInfo.getMobilePhone());
                newUserRecord.setAction(integralTypeEnum.MANUAL_ADDITION);
                customerPointsRecordMapper.insertCustomerPointsRecord(newUserRecord);
            }
        }
        // 更改电子卡手机号
        List<CustomerElectronicCard> oldCardList;
        List<CustomerElectronicCard> newCardList;
        if (StringUtils.equals("1", enterpriseUser.getCardUseRangeFlag())) {
            // 多站通用
            CustomerElectronicCard form1 = new CustomerElectronicCard();
            form1.setMobilePhone(oldAppUser.getMobilePhone());
            form1.setStationId(oldAppUser.getStationId());
            oldCardList = customerElectronicCardService.queryListOrderByCardType(form1);
            form1.setMobilePhone(newUserInfo.getMobilePhone());
            newCardList = customerElectronicCardService.queryListOrderByCardType(form1);
        } else {
            // 单站使用
            CustomerElectronicCard form1 = new CustomerElectronicCard();
            form1.setMobilePhone(oldAppUser.getMobilePhone());
            form1.setStationId2(stationUser.getStationId());
            oldCardList = customerElectronicCardService.queryListOrderByCardType(form1);
            form1.setMobilePhone(newUserInfo.getMobilePhone());
            newCardList = customerElectronicCardService.queryListOrderByCardType(form1);
        }
        for (CustomerElectronicCard oldCard : oldCardList) {
            if (oldCard.getAmt().compareTo(BigDecimal.ZERO)<=0) {
                // 电子卡余额为0，不处理
                continue;
            }
            CustomerElectronicCard newCard = null;
            for (CustomerElectronicCard c : newCardList) {
                if (StringUtils.equals(c.getCardOilsType(), oldCard.getCardOilsType())) {
                    newCard = c;
                    break;
                }
            }
            if (newCard == null) {
                newCard = new CustomerElectronicCard();
                newCard.setAmt(BigDecimal.ZERO);
                newCard.setMobilePhone(newUserInfo.getMobilePhone());
                newCard.setCustomerNo(newUserInfo.getMemberCode());
                newCard.setCustomerName(newUserInfo.getBlogNickName());
                newCard.setAmt(BigDecimal.ZERO);
                newCard.setCardOilsType(oldCard.getCardOilsType());
                newCard.setStationId(oldCard.getStationId());
                newCard.setStationId2(oldCard.getStationId2());
            }
            mergerElectronicCard(newCard,oldCard,stationUser);
        }
        // 更改充值立减活动金额
        List<ReductionActivityBalanceRecord> oldList;
        List<ReductionActivityBalanceRecord> newList;
        if (StringUtils.equals("1",enterpriseUser.getCardUseRangeFlag())) {
            ReductionActivityBalanceRecord form2 = new ReductionActivityBalanceRecord();
            form2.setMobilePhone(oldAppUser.getMobilePhone());
            form2.setEnterpriseId(oldAppUser.getStationId());
            oldList = reductionActivityBalanceRecordService.list(new QueryWrapper<>(form2));
            form2.setMobilePhone(newUserInfo.getMobilePhone());
            newList = reductionActivityBalanceRecordService.list(new QueryWrapper<>(form2));
        }else{
            ReductionActivityBalanceRecord form2 = new ReductionActivityBalanceRecord();
            form2.setMobilePhone(oldAppUser.getMobilePhone());
            form2.setStationId(stationUser.getStationId());
            oldList = reductionActivityBalanceRecordService.list(new QueryWrapper<>(form2));
            form2.setMobilePhone(newUserInfo.getMobilePhone());
            newList = reductionActivityBalanceRecordService.list(new QueryWrapper<>(form2));
        }
        for (ReductionActivityBalanceRecord oldRecord : oldList) {
            if (oldRecord.getBalance().compareTo(BigDecimal.ZERO)<=0) {
                // 立减优惠余额为0，不处理
                continue;
            }
            ReductionActivityBalanceRecord newRecord = null;
            for (ReductionActivityBalanceRecord c : newList) {
                if (StringUtils.equals(c.getCardOilsType(), oldRecord.getCardOilsType())) {
                    newRecord = c;
                    break;
                }
            }
            if (newRecord == null) {
                newRecord = new ReductionActivityBalanceRecord();
                newRecord.setUserId(newUserInfo.getUserId());
                newRecord.setMobilePhone(newUserInfo.getMobilePhone());
                newRecord.setRechargeAmt(BigDecimal.ZERO);
                newRecord.setBalance(BigDecimal.ZERO);
                newRecord.setCardOilsType(oldRecord.getCardOilsType());
                newRecord.setStationId(oldRecord.getStationId());
                newRecord.setEnterpriseId(oldRecord.getEnterpriseId());
                newRecord.setCreateTime(LocalDateTime.now());
                newRecord.setUpdateTime(LocalDateTime.now());
            }
            mergerBalanceReductionActivity(newRecord,oldRecord);
        }
    }

    private void mergerUserInfo(SysAppUserInfoUser newUser,SysAppUserInfoUser oldUser){
        newUser.setUserType(oldUser.getUserType());
        newUser.setMinaOpenid(oldUser.getMinaOpenid());
        //newUser.setGradeName(oldUser.getGradeName());
        newUser.setSexFlag(oldUser.getSexFlag());
        newUser.setRegisteDate(oldUser.getRegisteDate());

        newUser.setUpdateDate(oldUser.getUpdateDate());
        newUser.setUnionId(oldUser.getUnionId());

        //newUser.setSource(oldUser.getSource());
        newUser.setName(oldUser.getName());

        newUser.setBirthday(oldUser.getBirthday());

        newUser.setTruckNumber(oldUser.getTruckNumber());
        newUser.setICCard(oldUser.getICCard());

        newUser.setRegisteDate(oldUser.getRegisteDate());
        newUser.setFollowStatus(oldUser.getFollowStatus());
        newUser.setFirstStationId(oldUser.getFirstStationId());
        newUser.setRegisterStationId(oldUser.getRegisterStationId());
        newUser.setTruckBrand(oldUser.getTruckBrand());
        //newUser.setUserLevel(oldUser.getUserLevel());


        String memberCode=null;
        if (StringUtils.isNotBlank(oldUser.getMemberCode())) {
            memberCode = oldUser.getMemberCode();
        }
//        else{
//            memberCode = LocalDateUtils.format(LocalDate.now(),"yyMMdd")+RandomStringUtils.randomNumeric(5);
//        }
        newUser.setMemberCode(memberCode);
//        String yunhuaId;
//        if (StringUtils.isNotBlank(oldUser.getYunhuaUserId())) {
//            yunhuaId = oldUser.getYunhuaUserId();
//        }else{
//            yunhuaId = yunHuaPayUtils.sendUser(newUser.getMobilePhone());
//            if("".equals(yunhuaId)){
//                yunhuaId = null;
//            }
//        }
//        newUser.setYunhuaUserId(yunhuaId);
        newUser.setIntegral(MathUtil.add(newUser.getIntegral(),oldUser.getIntegral()));
        newUser.setGrowUpValue(MathUtil.add(newUser.getGrowUpValue(),oldUser.getGrowUpValue()));
    }

    private void mergerElectronicCard(CustomerElectronicCard newCard,CustomerElectronicCard oldCard,SysStationUser stationUser){
        BigDecimal oldCardAmt = oldCard.getAmt();
        BigDecimal oldCardPresentAmt = oldCard.getPresentAmt();
        newCard.setAmt(MathUtil.add(newCard.getAmt(), oldCardAmt));
        newCard.setPresentAmt(MathUtil.add(newCard.getPresentAmt(), oldCardPresentAmt));
        if (newCard.getId()==null) {
            customerElectronicCardService.insertCustomerElectronicCard(newCard);
        }else{
            customerElectronicCardService.updateCustomerElectronicCard(newCard);
        }
        // 清零旧电子卡余额
        CustomerElectronicCard updateCard = new CustomerElectronicCard();
        updateCard.setId(oldCard.getId());
        updateCard.setAmt(BigDecimal.ZERO);
        updateCard.setPresentAmt(BigDecimal.ZERO);
        customerElectronicCardService.updateCustomerElectronicCard(updateCard);
        // 添加余额明细记录
        CustomerCardUseRecord oldCardRecord = new CustomerCardUseRecord();
        oldCardRecord.setOrderNo(com.qujia.common.utils.StringUtils.generateOrdNo());
        oldCardRecord.setCustomerNo(oldCard.getCustomerNo());
        oldCardRecord.setCustomerName(oldCard.getCustomerName());
        oldCardRecord.setUsageType("-");
        oldCardRecord.setPayType(CardRecordType.MANUAL_SUB.getKey());
        oldCardRecord.setCardOilsType(oldCard.getCardOilsType());
        oldCardRecord.setAmt(oldCardAmt);
        oldCardRecord.setPresentAmt(oldCardPresentAmt);
        oldCardRecord.setBalance(BigDecimal.ZERO);
        oldCardRecord.setCreateTime(new Date());
        oldCardRecord.setStationId(Math.toIntExact(stationUser.getStationId()));
        oldCardRecord.setStatus("1");
        oldCardRecord.setMobilePhone(oldCard.getMobilePhone());
        oldCardRecord.setEnterpriseId(stationUser.getEnterpriseId());
        customerCardUseRecordMapper.insertCustomerCardUseRecord(oldCardRecord);
        CustomerCardUseRecord newCardRecord = new CustomerCardUseRecord();
        newCardRecord.setOrderNo(com.qujia.common.utils.StringUtils.generateOrdNo());
        newCardRecord.setCustomerNo(newCard.getCustomerNo());
        newCardRecord.setCustomerName(newCard.getCustomerName());
        newCardRecord.setUsageType("+");
        newCardRecord.setPayType(CardRecordType.MANUAL_ADD.getKey());
        newCardRecord.setCardOilsType(newCard.getCardOilsType());
        newCardRecord.setAmt(oldCardAmt);
        newCardRecord.setPresentAmt(oldCardPresentAmt);
        newCardRecord.setBalance(MathUtil.add(newCard.getAmt(),newCard.getPresentAmt()));
        newCardRecord.setCreateTime(new Date());
        newCardRecord.setStationId(Math.toIntExact(stationUser.getStationId()));
        newCardRecord.setStatus("1");
        newCardRecord.setMobilePhone(newCard.getMobilePhone());
        newCardRecord.setEnterpriseId(stationUser.getEnterpriseId());
        customerCardUseRecordMapper.insertCustomerCardUseRecord(newCardRecord);
    }

    private void mergerBalanceReductionActivity(ReductionActivityBalanceRecord newRecord,ReductionActivityBalanceRecord oldRecord){
        // newRecord充值金额设置成最大的一个
        if(newRecord.getRechargeAmt().compareTo(oldRecord.getRechargeAmt())<0){
            newRecord.setRechargeAmt(oldRecord.getRechargeAmt());
        }
        newRecord.setBalance(MathUtil.add(newRecord.getBalance(),oldRecord.getBalance()));
        reductionActivityBalanceRecordService.save(newRecord);
        // 清零旧数据
        ReductionActivityBalanceRecord update = new ReductionActivityBalanceRecord();
        update.setRabrId(oldRecord.getRabrId());
        update.setBalance(BigDecimal.ZERO);
        reductionActivityBalanceRecordService.updateById(update);
    }

    @Override
    @Transactional
    public String importCardExcelData(MultipartFile file) throws Exception {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String username = user.getUserName();
        boolean isAdmin = StringUtils.equals(username,"admin");
        // 是不是油企账号
        boolean isEnt = StringUtils.equals(user.getUserLevel(), UserConstants.LEVEL_TWO);
        InputStream is = file.getInputStream();
        ExcelUtil<CardExcelItem> excelUtil = new ExcelUtil<>(CardExcelItem.class);
        List<CardExcelItem> cardExcelItems = excelUtil.importExcel(is);
        is.close();
//        long count = cardExcelItems.stream().filter(c -> {
//            Long stationId = c.getStationId();
//            boolean b = stationId == null;
//            String phone = c.getMobilePhone();
//            b = b || StringUtils.isBlank(phone);
//            b = b || (isAdmin && (c.getEnterpriseId() == null));
//            return b;
//        }).count();
//        if (count>0) {
//            throw new CustomException("数据格式不对!");
//        }
        Map<Long, EnterpriseData> map = new HashMap<>();
        StringBuilder builder = new StringBuilder();
        int size = cardExcelItems.size();
        ImportContext ctx = new ImportContext(Math.min(size,BATCH_SIZE));
        for (int i = 0; i < size; i++) {
            appendNewLine(builder,i);
            CardExcelItem excelItem = cardExcelItems.get(i);
            if (excelItem == null) {
                builder.append("数据为空");
                ctx.failCount++;
                continue;
            }
            excelItem.setMobilePhone(StringUtils.trim(excelItem.getMobilePhone()));
            if (StringUtils.isBlank(excelItem.getMobilePhone())) {
                builder.append("导入失败!手机号为空");
                ctx.failCount++;
                continue;
            }
            Long enterpriseId = excelItem.getEnterpriseId();
            if (isAdmin) {
                if (enterpriseId == null) {
                    builder.append("导入失败!油企ID为空");
                    ctx.failCount++;
                    continue;
                }
            }else if(isEnt){
                Long ue = user.getEnterpriseId();
                if (enterpriseId != null && !enterpriseId.equals(ue)) {
                    builder.append("导入失败!非本油企ID");
                    ctx.failCount++;
                    continue;
                }
                enterpriseId = ue;
                excelItem.setEnterpriseId(enterpriseId);
            }else{
                builder.append("导入失败!");
                ctx.failCount++;
                continue;
            }
            EnterpriseData data = map.get(enterpriseId);
            if (data == null) {
                data = newImportData(enterpriseId);
                map.put(enterpriseId,data);
            }
            if (excelItem.getStationId() == null) {
                builder.append("导入失败!油站ID为空");
                ctx.failCount++;
                continue;
            }
            if(!data.containsStationId(excelItem.getStationId())){
                builder.append("导入失败!油企下油站ID不存在");
                ctx.failCount++;
                continue;
            }
            if (!data.enableCard) {
                builder.append("导入失败!油企未开启电子卡");
                ctx.failCount++;
                continue;
            }
            doImport(ctx,data,excelItem,user,builder);
            if (ctx.insertRecords.size()>=BATCH_SIZE) {
                insertOrUpdateToDB(ctx);
            }
        }
        insertOrUpdateToDB(ctx);
        return builder.insert(0,String.format("总数据：%d,导入成功：%d,导入失败：%d",size,size-ctx.failCount,ctx.failCount)).toString();
    }

    @Override
    public String importCardAndLabelUserExcelData(MultipartFile file,Long labelId) throws Exception {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String username = user.getUserName();
        boolean isAdmin = StringUtils.equals(username,"admin");
        // 是不是油企账号
        boolean isEnt = StringUtils.equals(user.getUserLevel(), UserConstants.LEVEL_TWO);
        InputStream is = file.getInputStream();
        ExcelUtil<LabelRuleUser> excelUtil = new ExcelUtil<>(LabelRuleUser.class);
        List<LabelRuleUser> cardExcelItems = excelUtil.importExcel(is);
        is.close();
//        long count = cardExcelItems.stream().filter(c -> {
//            Long stationId = c.getStationId();
//            boolean b = stationId == null;
//            String phone = c.getMobilePhone();
//            b = b || StringUtils.isBlank(phone);
//            b = b || (isAdmin && (c.getEnterpriseId() == null));
//            return b;
//        }).count();
//        if (count>0) {
//            throw new CustomException("数据格式不对!");
//        }
        Map<Long, EnterpriseData> map = new HashMap<>();
        StringBuilder builder = new StringBuilder();
        int size = cardExcelItems.size();
        ImportContext ctx = new ImportContext(Math.min(size,BATCH_SIZE));
        for (int i = 0; i < size; i++) {
            appendNewLine(builder,i);
            LabelRuleUser excelItem = cardExcelItems.get(i);
            if (excelItem == null) {
                builder.append("数据为空");
                ctx.failCount++;
                continue;
            }
            excelItem.setMobilePhone(StringUtils.trim(excelItem.getMobilePhone()));
            if (StringUtils.isBlank(excelItem.getMobilePhone())) {
                builder.append("导入失败!手机号为空");
                ctx.failCount++;
                continue;
            }
            if (!validatePhoneNumber(excelItem.getMobilePhone())) {
                builder.append("导入失败!手机号格式不正确");
                ctx.failCount++;
                continue;
            }
            CustomerLabel cl=new CustomerLabel();
            cl.setPhone(excelItem.getMobilePhone());
            cl.setEnterpriseId(user.getEnterpriseId());
            Integer count = customerLabelMapper.countCustomerLabel(cl);
            if(count>0){
                builder.append("导入失败!手机号已存在");
                ctx.failCount++;
                continue;
            }

            Long enterpriseId = excelItem.getEnterpriseId();
            if (isAdmin) {
                if (enterpriseId == null) {
                    builder.append("导入失败!油企ID为空");
                    ctx.failCount++;
                    continue;
                }
            }else if(isEnt){
                Long ue = user.getEnterpriseId();
                if (enterpriseId != null && !enterpriseId.equals(ue)) {
                    builder.append("导入失败!非本油企ID");
                    ctx.failCount++;
                    continue;
                }
                enterpriseId = ue;
                excelItem.setEnterpriseId(enterpriseId);
            }else{
                builder.append("导入失败!");
                ctx.failCount++;
                continue;
            }
            EnterpriseData data = map.get(enterpriseId);
            if (data == null) {
                data = newImportData(enterpriseId);
                map.put(enterpriseId,data);
            }
            if (excelItem.getStationId() == null) {
                builder.append("导入失败!油站ID为空,或对应油站不存在");
                ctx.failCount++;
                continue;
            }
            if(!data.containsStationId(excelItem.getStationId())){
                builder.append("导入失败!油企下油站ID不存在");
                ctx.failCount++;
                continue;
            }
            if (!data.enableCard) {
                builder.append("导入失败!油企未开启电子卡");
                ctx.failCount++;
                continue;
            }
            SysAppUserInfoUser userInfo = addOrCreatedUserInfo(ctx,data, excelItem);
            CustomerLabel customerLabel=new CustomerLabel();
            customerLabel.setLabelId(labelId.intValue());
            customerLabel.setPhone(userInfo.getMobilePhone());
            customerLabel.setEnterpriseId(excelItem.getEnterpriseId());
            customerLabel.setDelFlag("0");

            List<CustomerLabel> customerLabels = customerLabelMapper.selectCustomerLabelList(customerLabel);
            if(customerLabels.size()==0){
                customerLabelMapper.insertCustomerLabel(customerLabel);
            }

            if (userInfo.getUserId() == null) {
                builder.append("新增用户,");
            }

            if (ctx.insertUsers.size()>=BATCH_SIZE) {
                insertOrUpdateToDB(ctx);
            }
        }
        insertOrUpdateToDB(ctx);
        return builder.insert(0,String.format("总数据：%d,导入成功：%d,导入失败：%d",size,size-ctx.failCount,ctx.failCount)).toString();
    }

    private  boolean validatePhoneNumber(String phoneNumber) {
        Pattern pattern = Pattern.compile("^1[0-9]{10}$"); // 定义手机号格式的正则表达式
        Matcher matcher = pattern.matcher(phoneNumber);
        return matcher.matches();
    }

    private void doImport(ImportContext ctx,EnterpriseData enterpriseData, CardExcelItem excelItem,SysUser sysUser, StringBuilder builder){
        SysAppUserInfoUser userInfo = addOrCreatedUserInfo(ctx,enterpriseData, excelItem);
//        if (userInfo == null) {
//            builder.append("导入失败!手机号重复");
//            ctx.failCount++;
//            return;
//        }
        if (userInfo.getUserId() == null) {
            builder.append("新增用户,");
        }
//        else{
//            builder.append("导入积分成功,");
//        }
        int i = addOrCreateCardAmt(ctx,excelItem, enterpriseData,userInfo,sysUser);
        if (i==0) {
            builder.append("导入的余额为0");
        }else{
            builder.append("导入余额成功");
        }
    }

    private void insertOrUpdateToDB(ImportContext ctx) {
        List<SysAppUserInfoUser> updateUsers = ctx.updateUsers;
        for (SysAppUserInfoUser user : updateUsers) {
            appUserInfoUserMapper.updateAppUserInfo(user);
        }
        List<CustomerElectronicCard> updateCards = ctx.updateCards;
        for (CustomerElectronicCard card : updateCards) {
            customerElectronicCardService.incrCustomerElectronicCardBalance(card.getAmt(),card.getPresentAmt(), card);
        }
        if (!ctx.insertCardExcels.isEmpty()) {
            cardExcelImportMapper.insertBatch(ctx.insertCardExcels);
        }
        if (!ctx.insertRecords.isEmpty()) {
            customerCardUseRecordMapper.insertBatch(ctx.insertRecords);
            //用户参与充值立减活动
            for (CustomerCardUseRecord insertRecord : ctx.insertRecords) {
                if(insertRecord.getUsageType().equals("+")){
                    activityMessagePushRecordService.sendWxMessage(ActivityMessagePushRecord.TOPIC_REDUCTION_ACTIVITY, JSON.toJSONString(insertRecord), WxConsumptionMessageEnum.RECHARGE_REDUCTION_ACTIVITY);
                }
            }

        }
        if (!ctx.insertCards.isEmpty()) {
            customerElectronicCardService.insertBatch(ctx.insertCards);
        }
        if (!ctx.insertUsers.isEmpty()) {
            appUserInfoUserMapper.insertBatch(ctx.insertUsers);
        }
        ctx.clearAll();
    }

    private void appendNewLine(StringBuilder builder,int index){
        builder.append("\n第").append(index+2).append("行:");
    }

    private EnterpriseData newImportData(Long enterpriseId){
        EnterpriseData data = new EnterpriseData();
        CustomerCardSetting setting = new CustomerCardSetting();
        setting.setEnterpriseId(enterpriseId);
        List<CustomerCardSetting> list = customerCardSettingService.selectCustomerCardSettingList(setting);
        if (list.size()>0) {
            CustomerCardSetting cardSetting = list.get(0);
            if (StringUtils.isNotBlank(cardSetting.getCardOilsType())) {
                String[] types = cardSetting.getCardOilsType().split(",");
                if (types.length > 0) {
                    data.setting = cardSetting;
                    data.cardTypes = types;
                }
            }
        }
        data.enableCard = data.setting != null && StringUtils.equals("1", data.setting.getCardEnabledFlag());
        data.cardUseForAll = data.setting != null && StringUtils.equals("1",data.setting.getCardUseRangeFlag());
        data.enterpriseId = enterpriseId;
        data.createSet();
        SysStationUser form = new SysStationUser();
        form.setEnterpriseId(enterpriseId);
        form.setDeleteStatus("0");
        form.setStatus("1");
        List<SysStationUser> stationList = sysStationUserMapper.selectSysStationUserList(form);
        data.stationIdSet = new HashSet<>();
        for (SysStationUser stationUser : stationList) {
            data.stationIdSet.add(stationUser.getStationId());
        }
        return data;
    }

    private SysAppUserInfoUser addOrCreatedUserInfo(ImportContext ctx,EnterpriseData enterpriseData,CardExcelItem excelItem){
        if (enterpriseData.containsPhone(excelItem.getStationId(),excelItem.getMobilePhone())) {
            SysAppUserInfoUser user = new SysAppUserInfoUser();
            if (!enterpriseData.newUserPhone.contains(excelItem.getMobilePhone())) {
                user.setUserId(1L);
            }
            user.setMobilePhone(excelItem.getMobilePhone());
            user.setStationId(excelItem.getEnterpriseId());
            return user;
        }
        enterpriseData.addPhone(excelItem.getStationId(),excelItem.getMobilePhone());
        SysAppUserInfoUser userInfo = new SysAppUserInfoUser();
        userInfo.setMobilePhone(excelItem.getMobilePhone());
        userInfo.setStationId(excelItem.getEnterpriseId());
        SysAppUserInfoUser one = appUserInfoUserMapper.getOne(userInfo);
        if (one == null) {
            one = new SysAppUserInfoUser();
            one.setStationId(excelItem.getEnterpriseId());
            one.setMobilePhone(excelItem.getMobilePhone());
            one.setIntegral( excelItem.getIntegral() == null ? 0L : Long.valueOf(excelItem.getIntegral()));
            one.setGrowUpValue( excelItem.getGrowUpValue() == null ? 0L : Long.valueOf(excelItem.getGrowUpValue()));
            ctx.insertUsers.add(one);
            enterpriseData.newUserPhone.add(excelItem.getMobilePhone());
        }
/*        else{
            SysAppUserInfoUser info = new SysAppUserInfoUser();
            info.setUserId(one.getUserId());
            info.setStationId(one.getStationId());
            info.setMobilePhone(one.getMobilePhone());
            long excelIntegral = excelItem.getIntegral() == null ? 0L : excelItem.getIntegral();
            long integral = (one.getIntegral() == null ? 0L:one.getIntegral()) + excelIntegral;
            info.setIntegral(integral);
            long excelGrow = excelItem.getGrowUpValue() == null ? 0L : excelItem.getGrowUpValue();
            long growUpValue = (one.getGrowUpValue() == null ? 0:one.getGrowUpValue()) + excelGrow ;
            info.setGrowUpValue(growUpValue);
            one = info;
            if(excelIntegral > 0 || excelGrow >0 ){
                ctx.updateUsers.add(one);
            }
        }*/
        return one;
    }


    private SysAppUserInfoUser addOrCreatedUserInfo(ImportContext ctx,EnterpriseData enterpriseData,LabelRuleUser excelItem){
        if (enterpriseData.containsPhone(excelItem.getStationId(),excelItem.getMobilePhone())) {
            SysAppUserInfoUser user = new SysAppUserInfoUser();
            if (!enterpriseData.newUserPhone.contains(excelItem.getMobilePhone())) {
                user.setUserId(1L);
            }
            user.setMobilePhone(excelItem.getMobilePhone());
            user.setStationId(excelItem.getEnterpriseId());
            return user;
        }
        enterpriseData.addPhone(excelItem.getStationId(),excelItem.getMobilePhone());
        SysAppUserInfoUser userInfo = new SysAppUserInfoUser();
        userInfo.setMobilePhone(excelItem.getMobilePhone());
        userInfo.setStationId(excelItem.getEnterpriseId());
        SysAppUserInfoUser one = appUserInfoUserMapper.getOne(userInfo);
        if (one == null) {
            one = new SysAppUserInfoUser();
            one.setStationId(excelItem.getEnterpriseId());
            one.setMobilePhone(excelItem.getMobilePhone());
            one.setIntegral( 0l);
            one.setGrowUpValue( 0l);
            ctx.insertUsers.add(one);
            enterpriseData.newUserPhone.add(excelItem.getMobilePhone());
        }
        return one;
    }

    private int addOrCreateCardAmt(ImportContext ctx,CardExcelItem excelItem, EnterpriseData enterpriseData,SysAppUserInfoUser userInfo,SysUser sysUser){
        List<CustomerElectronicCard> cardList;
        String phone = excelItem.getMobilePhone();
        if(enterpriseData.cardUseForAll){
            cardList = customerElectronicCardService.getCustomerElectronicCardListForEnterprise(phone, enterpriseData.cardTypes, enterpriseData.enterpriseId);
        }else{
            cardList = customerElectronicCardService.getCustomerElectronicCardListForStation(phone, enterpriseData.cardTypes, excelItem.getStationId());
        }
        List<CustomerElectronicCard> addedList = new ArrayList<>();
        for (String cardType : enterpriseData.cardTypes) {
            BigDecimal amt = null;
            switch (cardType){
                case "0":
                    amt = excelItem.getGenericAmt();
                    break;
                case "1":
                    amt = excelItem.getGasAmt();
                    break;
                case "2":
                    amt = excelItem.getDieselAmt();
                    break;
                case "3":
                    amt = excelItem.getLngAmt();
                    break;
                case "4":
                    amt = excelItem.getCngAmt();
                    break;
            }
            if (amt == null || amt.compareTo(BigDecimal.ZERO) ==0) {
                continue;
            }
            CustomerElectronicCard card = new CustomerElectronicCard();
            card.setCardOilsType(cardType);
            card.setMobilePhone(phone);
            card.setAmt(amt);
            if (enterpriseData.cardUseForAll) {
                card.setStationId(excelItem.getEnterpriseId());
            }else{
                card.setStationId2(excelItem.getStationId());
            }
            addedList.add(card);
        }
        int i = 0;
        for (CustomerElectronicCard card : addedList) {
            String type = card.getCardOilsType();
            Optional<CustomerElectronicCard> first = cardList.stream().filter(c -> StringUtils.equals(c.getCardOilsType(), type)).findFirst();
            if (!first.isPresent()) {
                // 没有卡，创建
                if (card.getAmt().compareTo(BigDecimal.ZERO) <=0) {
                    continue;
                }
                card.setCreateTime(ctx.nowTime);
                // 计算赠送金额
                CalPresentAmt calPresentAmt = customerCardSettingDetailService.calPresentAmt(type, card.getAmt(), excelItem.getStationId(), userInfo.getStationId(), "xj",false);
                card.setPresentAmt(calPresentAmt.getPresentAmt());
                CustomerCardUseRecord customerCardUseRecord = newRecord(ctx, card.getAmt(), card.getPresentAmt(),MathUtil.add(card.getAmt(),card.getPresentAmt()), card.getCardOilsType(), userInfo, excelItem.getStationId(),true);
                customerCardUseRecord.setCcsdId(calPresentAmt.getCcsdId());

                ctx.insertCards.add(card);
                ctx.insertRecords.add(customerCardUseRecord);
            }else{
                // 有卡，更新
                CustomerElectronicCard oldCard = first.get();
                card.setId(oldCard.getId());
                BigDecimal oriAmt = card.getAmt();  // 操作金额
                CalPresentAmt calPresentAmt;
                BigDecimal afterBalance;
                BigDecimal opAmt;
                BigDecimal opPreAmt;
                boolean add;
                if (oriAmt.compareTo(BigDecimal.ZERO)>0) {
                    // 操作金额大于0，计算赠送金额
                    add = true;
                    calPresentAmt = customerCardSettingDetailService.calPresentAmt(type, card.getAmt(), excelItem.getStationId(), userInfo.getStationId(), "xj",false);
                    card.setPresentAmt(calPresentAmt.getPresentAmt());
                    opAmt = card.getAmt();
                    opPreAmt = card.getPresentAmt();
                    afterBalance = MathUtil.add(card.getAmt(),card.getPresentAmt()).add(MathUtil.add(oldCard.getAmt(),oldCard.getPresentAmt()));
                }else{
                    // 小于0
                    add = false;
                    calPresentAmt = new CalPresentAmt();
                    ElectronicCardSubRes res = oldCard.subtractAmount(oriAmt.negate());
                    if (res.isSuccess()) {
                        // 余额够扣减
                        card.setAmt(res.getAmt().negate());
                        card.setPresentAmt(res.getPresentAmt().negate());
                        afterBalance = MathUtil.add(oldCard.getAmt(),oldCard.getPresentAmt());
                    }else{
                        // 余额不够扣减,卡余额置为0
                        card.setAmt(oldCard.getAmt().negate());
                        card.setPresentAmt(oldCard.getPresentAmt().negate());
                        afterBalance = BigDecimal.ZERO;
                    }
                    opAmt = card.getAmt();
                    opPreAmt = card.getPresentAmt();
                }
                CustomerCardUseRecord customerCardUseRecord = newRecord(ctx, opAmt,opPreAmt,afterBalance, card.getCardOilsType(), userInfo, excelItem.getStationId(),add);
                customerCardUseRecord.setCcsdId(calPresentAmt.getCcsdId());
                ctx.updateCards.add(card);
                ctx.insertRecords.add(customerCardUseRecord);
                CustomerElectronicCard card1 = new CustomerElectronicCard();
                card1.setMobilePhone(card.getMobilePhone());
                card1.setAmt(oriAmt);
                card1.setCardOilsType(card.getCardOilsType());
                card = card1;
            }
            CardExcelImport cardExcelImport = newCardExcel(ctx,excelItem, card);
            cardExcelImport.setCreateBy(String.valueOf(sysUser.getUserId()));
            ctx.insertCardExcels.add(cardExcelImport);
            i++;
        }
        return i;
    }

    private CustomerCardUseRecord newRecord(ImportContext ctx,BigDecimal amt,BigDecimal presentAmt,BigDecimal balance,String cardType,SysAppUserInfoUser userInfo,Long stationId,boolean add){
        CustomerCardUseRecord record = new CustomerCardUseRecord();
        record.setEnterpriseId(userInfo.getStationId());
        record.setStationId(stationId.intValue());
        record.setServiceCharge(BigDecimal.ZERO);
        record.setMobilePhone(userInfo.getMobilePhone());
        if (StringUtils.isNotBlank(userInfo.getMemberCode())) {
            record.setCustomerNo(userInfo.getMemberCode());
        }
        if (StringUtils.isNotBlank(userInfo.getBlogNickName())) {
            record.setCustomerName(userInfo.getBlogNickName());
        }
        record.setCardOilsType(cardType);
        record.setAmt(amt.abs());
        record.setPresentAmt(presentAmt.abs());
        record.setStatus("1");
        record.setBalance(balance);
        record.setUsageType(add ? "+":"-");
        record.setPayType(add ? CardRecordType.MANUAL_ADD.getKey() : CardRecordType.MANUAL_SUB.getKey());
        record.setCreateTime(ctx.nowTime);
        record.setOrderNo(com.qujia.common.utils.StringUtils.generateOrdNo());
        return record;
    }

    private CardExcelImport newCardExcel(ImportContext ctx,CardExcelItem excelItem,CustomerElectronicCard card){
        CardExcelImport cardExcelImport = new CardExcelImport();
        cardExcelImport.setEnterpriseId(excelItem.getEnterpriseId());
        cardExcelImport.setStationId(excelItem.getStationId().intValue());
        cardExcelImport.setBalance(card.getAmt());
        cardExcelImport.setImportStatus("0");
        cardExcelImport.setGrowValue(excelItem.getGrowUpValue());
        cardExcelImport.setIntegral(excelItem.getIntegral());
        cardExcelImport.setPhoneNumber(card.getMobilePhone());
        cardExcelImport.setCardType(card.getCardOilsType());
        cardExcelImport.setCreateTime(ctx.nowTime);
        return cardExcelImport;
    }


    /*
     * 微信公众号推送
     * @param appId
     * @param appSecret
     * @param templateId
     * @param openId
     * @param wxMpTemplateDataList
     */
    public Integer push(  String openId,SysEnterpriseUser sysEnterpriseUser,String templateId,String ponts,String  addPonits){

        //创建对象
        WxMpInMemoryConfigStorage wxMpInMemoryConfigStorage = new WxMpInMemoryConfigStorage();
        Date date=new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //公众号token缓存处理
        //String tokenCache = weiXinUserUtil.getTokenByRedisCache(appId, appSecret);
        String tokenCache ="";

        String tokeurl="";

        wxMpInMemoryConfigStorage.setAppId(sysEnterpriseUser.getGzhAppId());
        wxMpInMemoryConfigStorage.setSecret(sysEnterpriseUser.getGzhAppSecret());

        if("/mnt/uploadfile/images//upload".equals(QuJiaConfig.getUploadPath())){


            tokeurl="https://mp.huijy.net/prod/getAccessTokenFromSaas";

        }else {

            tokeurl="https://mp.huijy.net/prod/getAccessTokenFromSaas";
        }


        tokenCache  = redisCache.getCacheObject("access_token_"+sysEnterpriseUser.getGzhAppId());
        if("".equals(tokenCache)||tokenCache==null){

            String tokenJson="{\n" +
                    "    \"appId\":\""+sysEnterpriseUser.getGzhAppId()+"\",\n" +
                    "    \"appSecret\":\""+sysEnterpriseUser.getGzhAppSecret()+"\"\n" +
                    "}";
            JSONObject tokenmessage= HttpRequestUtil.getHttpsRequestData(tokeurl,"POST",tokenJson);
            Integer mm1=tokenmessage.getInteger("retCode");

            tokenCache=tokenmessage.getString("data");
        }
        String url1="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+tokenCache;
        String method="POST";
        String mes="    {\n" +
                "           \"touser\":\""+openId+"\",\n" +
                "           \"template_id\":\""+templateId+"\",\n" +
                "           \"data\":{\n" +
                "                   \"first\": {\n" +
                "                       \"value\":\"恭喜获得后台赠送积分!\",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   },\n" +
                "                   \"time\":{\n" +
                "                       \"value\":\""+sdf.format(date)+"\",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   },\n" +
                "                   \"type\":{\n" +
                "                       \"value\":\""+"积分变动"+"\",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   },\n" +
                "                   \"Point\":{\n" +
                "                       \"value\":\""+addPonits+"\",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   },\n" +
                "                   \"From\":{\n" +
                "                       \"value\":\""+sysEnterpriseUser.getEnterpriseName()+"\",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   },\n" +
                "                   \"remark\":{\n" +
                "                       \"value\":\""+"截止到目前，可用积分值为"+ponts+"积分"+"\",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   }\n" +
                "           }\n" +
                "       }";


        JSONObject message= HttpRequestUtil.getHttpsRequestData(url1,method,mes);
        if(!"0".equals(message.getString("errcode"))){
            return 0;
        }else {
            return 1;
        }


    }






    /**
     * 字符串进行加密
     */
    public static String useMD5(String passWord) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(passWord.getBytes());
            return getHashString(digest);

        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    private static String getHashString(MessageDigest digest) {
        StringBuilder builder = new StringBuilder();
        for (byte b : digest.digest()) {
            builder.append(Integer.toHexString((b >> 4) & 0xf));
            builder.append(Integer.toHexString(b & 0xf));
        }
        return builder.toString().toLowerCase();
    }


    private static class EnterpriseData {
        CustomerCardSetting setting;
        Set<Long> stationIdSet;
        Set<String> phoneSet;//已处理过手机号，多站通用时不为null
        Set<String> newUserPhone;//新增用户手机号
        Map<Long,Set<String>> stationPhoneMap;//已处理过手机号，单站通用时不为null

        String[] cardTypes;

        Long enterpriseId;

        boolean enableCard;

        boolean cardUseForAll;

        public boolean containsStationId(Long stationId){
            return stationIdSet.contains(stationId);
        }

        //检查是否为已处理过的手机号
        public boolean containsPhone(Long stationId,String phone){
            Set<String> ps = getPhoneSet(stationId);
            return ps.contains(phone);
        }


        public void addPhone(Long stationId,String phone){
            getPhoneSet(stationId).add(phone);
        }

        public Set<String> getPhoneSet(Long stationId){
            Set<String> ps;
            if (cardUseForAll) {
                ps = phoneSet;
            }else{
                Set<String> ss = stationPhoneMap.get(stationId);
                if(ss == null){
                    ss = new HashSet<>();
                    stationPhoneMap.put(stationId,ss);
                }
                ps = ss;
            }
            return ps;
        }

        public void createSet(){
            if (!enableCard) {
                return;
            }
            newUserPhone = new HashSet<>();
            if (!cardUseForAll) {
                stationPhoneMap = new HashMap<>();
            }else{
                phoneSet = new HashSet<>();
            }
        }

    }

    private static class ImportContext{
        List<CustomerElectronicCard> insertCards;
        List<CustomerElectronicCard> updateCards;
        List<SysAppUserInfoUser> insertUsers;
        List<SysAppUserInfoUser> updateUsers;
        List<CustomerCardUseRecord> insertRecords;
        List<CardExcelImport> insertCardExcels;
        int failCount;
        Date nowTime;

        public ImportContext(int batchSize) {
            insertCards = Lists.newArrayListWithCapacity(batchSize);
            updateCards = Lists.newArrayListWithCapacity(batchSize);
            insertUsers = Lists.newArrayListWithCapacity(batchSize);
            updateUsers = Lists.newArrayListWithCapacity(batchSize);
            insertRecords = Lists.newArrayListWithCapacity(batchSize);
            insertCardExcels = Lists.newArrayListWithCapacity(batchSize);
            nowTime = new Date();
        }

        public void clearAll(){
            insertCards.clear();
            updateCards.clear();
            insertUsers.clear();
            updateUsers.clear();
            insertRecords.clear();
            insertCardExcels.clear();
        }
    }

}
